import copy
import os
from utils.csv_util import read_csv_file
from utils.yaml_util import read_testcase_yaml
from string import Template

current_path = os.path.dirname(__file__).split("core")[0]


def load_yaml_files(file_name):
    yaml_caseinfos = []
    yaml_file_path = os.path.join(current_path, file_name)
    for filename in os.listdir(yaml_file_path):
        if filename.startswith("test_") and filename.endswith(".yaml"):
            yaml_caseinfos.append(read_testcase_yaml(filename)[0])
    return yaml_caseinfos


def yaml_case_parser(case_file_path):
    all_caseinfos = []
    yaml_caseinfos = load_yaml_files(case_file_path)
    for caseinfo in yaml_caseinfos:
        if "parameters" in caseinfo.keys():
            csv_file_path = caseinfo["parameters"]["csv_file_path"]
            datas = read_csv_file(csv_file_path)
            for data in datas:
                new_case = copy.deepcopy(caseinfo)
                all_caseinfos.append(replace_csv_placeholders(caseinfo, [data]))
                caseinfo = new_case
        else:
            all_caseinfos.append(caseinfo)
    return all_caseinfos


def replace_csv_placeholders(yaml_data, csv_data):
    # 递归函数，用于替换 yaml 数据中的占位符
    def replace_recursive(data, csv_dict):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, str) and '$csv{' in value and '}' in value:
                    placeholder = value[5:-1]  # 提取占位符中的变量名
                    if placeholder in csv_dict:
                        data[key] = csv_dict[placeholder]
                else:
                    replace_recursive(value, csv_dict)
        elif isinstance(data, list):
            for i in range(len(data)):
                replace_recursive(data[i], csv_dict)
    for csv_row in csv_data:
        replace_recursive(yaml_data, csv_row)
    return yaml_data



def case_refresh(target, refresh_value):
    if target is None: return None
    return eval(Template(str(target)).safe_substitute(refresh_value))